﻿using System.Data.SQLite;
using System.Windows;
using System.Windows.Controls;
using Winform = System.Windows.Forms;
using WpfApp1.Model;
using WpfApp1.ViewModel;

namespace WpfApp1
{
    /// <summary>
    /// ruleslist.xaml 的交互逻辑
    /// </summary>
    public partial class Ruleslist : Window
    {
        static RulesViewModel globalRulesViewModel;
        string oldprefix;
        string oldpath;
        long id;

        public Ruleslist()
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            InitializeComponent();

            Initlist();
        }

        public void Initlist()
        {
            RulesViewModel rulesViewModel = new RulesViewModel();
            main.DataContext = rulesViewModel;
            list.DataContext = rulesViewModel.Rules;
            globalRulesViewModel = rulesViewModel;
        }

        private void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //MessageBox.Show(((Rule)list.CurrentItem).Prefix);

        }


        private void Textinput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            //MessageBox.Show(((Rule)list.SelectedItem).Directorypath);
        }

        private void EditEnd(object sender, DataGridCellEditEndingEventArgs e)
        {
            string value = (e.EditingElement as TextBox).Text;
            string column = e.Column.Header.ToString();
            Rule rule = (Rule)list.SelectedItem;

            if (value.Length == 0)
            {
                MessageBox.Show("请填写前缀");
                Initlist();
                return;
            }

            if (column == "前缀")
            {
                rule.Prefix = value;
            }
            if (column == "映射目录")
            {
                rule.Directorypath = value;
            }

            if (rule.Prefix == null && rule.Directorypath == null)
            {
                MessageBox.Show("信息不能为空");
                Initlist();
                return;
            }

            string sql;
            if (rule.Id > 0)
            {
                sql = "update rules set prefix=\"" + rule.Prefix + "\",directorypath=\"" + rule.Directorypath + "\" where id=" + rule.Id;
            }
            else
            {
                sql = "insert into rules (prefix,directorypath) values (\"" + rule.Prefix + "\",\"" + rule.Directorypath + "\")";
            }

            // 检查重复
            if (!Precheck(rule.Id, rule.Prefix))
            {
                return;
            }

            SQLiteCommand command = new SQLiteCommand(sql, MainWindow.connection);

            if (command.ExecuteNonQuery() > 0)
            {
                MessageBox.Show("操作成功");
                Initlist();
            }
            else
            {
                MessageBox.Show("操作失败");
                Initlist();
                MessageBox.Show(command.CommandText);
            }
        }

        private void Selectdir(object sender, RoutedEventArgs e)
        {
            Winform.FolderBrowserDialog dialog = new Winform.FolderBrowserDialog();
            if (dialog.ShowDialog() == Winform.DialogResult.OK)
            {
                Rule ruleSelect = new Rule()
                {
                    Id = 0,
                    Prefix = "",
                    Directorypath = ""
                };
                if (list.Items.Count > list.SelectedIndex + 1)
                {
                    ruleSelect = (Rule)list.SelectedItem;
                }

                id = ruleSelect.Id;

                string newpath = dialog.SelectedPath;

                if (ruleSelect.Directorypath != newpath)
                {
                    string sql;
                    if (id <= 0)
                    {
                        sql = "insert into rules (prefix,directorypath) values (\"" + ruleSelect.Prefix + "\",\"" + newpath + "\")";
                    }
                    else
                    {
                        sql = "update rules set directorypath=\"" + newpath + "\" where id=" + id;
                    }

                    if (!Precheck(id, ruleSelect.Prefix))
                    {
                        return;
                    }

                    SQLiteCommand command = new SQLiteCommand(sql, MainWindow.connection);
                    if (command.ExecuteNonQuery() > 0)
                    {
                        Initlist();
                        MessageBox.Show("操作成功");
                    }
                    else
                    {
                        MessageBox.Show("操作失败");
                    }
                }

            }
        }

        private void BeginEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            Rule oldrule = (Rule)e.Row.Item;
            oldprefix = oldrule.Prefix;
            id = oldrule.Id;
            oldpath = oldrule.Directorypath;
        }

        private void Removerule(object sender, RoutedEventArgs e)
        {
            Rule rule = (Rule)list.SelectedItem;
            long id = rule.Id;
            string delsql = "delete from rules where id=" + id;
            SQLiteCommand command = new SQLiteCommand(delsql, MainWindow.connection);
            if (command.ExecuteNonQuery() > 0)
            {
                MessageBox.Show("移除成功");
            }
            else
            {
                MessageBox.Show("移除失败");
            }
        }

        private void WindowClose(object sender, System.ComponentModel.CancelEventArgs e)
        {

        }

        public bool Precheck(long id, string prefix)
        {
            if (prefix == "")
            {
                MessageBox.Show("请先指定前缀");
                Initlist();
                return false;
            }

            string prechecksql = "select 1 from rules where prefix=\"" + prefix + "\" and id!=" + id;
            SQLiteCommand checkcommand = new SQLiteCommand(prechecksql, MainWindow.connection);
            if (checkcommand.ExecuteScalar() != null)
            {
                MessageBox.Show("您已经创建了相似规则，请修改");
                Initlist();
                return false;
            }

            return true;
        }

        private void InitNewitem(object sender, InitializingNewItemEventArgs e)
        {
        }

        private void AddNew(object sender, AddingNewItemEventArgs e)
        {
            //MessageBox.Show((sender as Rule).Prefix);
        }

        // 点击选择文件夹
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Winform.FolderBrowserDialog dialog = new Winform.FolderBrowserDialog();
            if (dialog.ShowDialog() == Winform.DialogResult.OK)
            {
                string new_dict = dialog.SelectedPath;
                string old_path = globalRulesViewModel.Dict_select;

                if (new_dict.Equals(old_path))
                {
                    return;
                }

                dictselect.Text = new_dict;
                string sql_old_pass = "select * from select_dic where directorypath=\"" + new_dict + "\"";
                SQLiteCommand command = new SQLiteCommand(sql_old_pass, MainWindow.connection);
                SQLiteDataReader reader = command.ExecuteReader();
                if (reader.Read())
                {
                    string sql_update = "update select_dic set is_last=1 where id=" + (long)reader["id"];
                    command = new SQLiteCommand(sql_update, MainWindow.connection);
                    command.ExecuteNonQuery();
                    return;
                }
                else
                {
                    string sql_update = "update select_dic set is_last=0 where id=" + globalRulesViewModel.Dict_select_id;
                    command = new SQLiteCommand(sql_update, MainWindow.connection);
                    command.ExecuteNonQuery();
                }

                string sql_insert = "insert into select_dic (directorypath,is_last) values(\"" + new_dict + "\",1)";
                command = new SQLiteCommand(sql_insert, MainWindow.connection);
                command.ExecuteNonQuery();
            }

        }
    }
}
